/*
 * Author: kael http://weibo.com/loskael
 */
package los.kael.fix;

import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;

import los.kael.file.FileWriterFromStringBuffer;
import los.kael.image.Images;
import los.kael.image.Position;

/**
 * 
 * @author kael http://weibo.com/loskael
 * @version $FileName: sprites.java $Date: 2011-11-5 下午2:55:48 -0400 2011
 * @since 1.0
 * 
 */
public class Sprites {
	private BufferedImage bi;
	private Position pos;
	private int width;
	private int height;
	private Hashtable<String, Images> imgTable = new Hashtable<String, Images>();
	private Images image;
	private StringBuffer sb = new StringBuffer();

	public Sprites(List<String> fileList, String path, String outputFilename) throws IOException {
		sb.append("." + outputFilename + "{background-image:url(../images/" + outputFilename + ".png)}\n");
		pos = new Position(fileList);
		width = pos.getMaxWidth();
		height = pos.getAllHeight();
		imgTable = pos.getImgTable();
		bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 设置背景透明
		Graphics2D g2d = bi.createGraphics();
		bi = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		g2d.dispose();
		// 绘制图片
		g2d = bi.createGraphics();
		Iterator<String> it = fileList.iterator();
		String fileName = null;
		while (it.hasNext()) {
			fileName = it.next().toString();
			System.out.println("file: " + fileName);
			image = imgTable.get(fileName);
			// 排除repeat-y
			if(image.getRepeatAndFloat() == Images.REPEAT_Y){
				continue;
			}
			// 重复repeat-x
			if (image.getRepeatAndFloat() == Images.REPEAT_X) {
				int px = image.getPositionX();
				int pw = image.getWidth();
				double times = (double)width / (double)pw;
				while(times > 0){
					g2d.drawImage(image.getImage(), px, image.getPositionY(), null);
					px += pw;
					times -= 1.0;
				}
			} else {
				g2d.drawImage(image.getImage(), image.getPositionX(), image.getPositionY(), null);
			}
			sb.append(image.toString());
		}
		g2d.dispose();
		File output = new File(path + "images/" + outputFilename + ".png");
		ImageIO.write(bi, "png", output);
		new FileWriterFromStringBuffer(sb, path + "css/" + outputFilename + ".css");
	}
}
